package service

import (
	"context"
	"fmt"
	"github.com/astaxie/beego/orm"
	"graduation/database"
	"graduation/design"
)

type AdminService struct {
}

func (self AdminService) ListAdmin(ctx context.Context, message *design.Empty) (*design.AdminList, error) {
	o := orm.NewOrm()
	res := &[]database.User{}
	_, err := o.QueryTable("user").RelatedSel("role").All(res)
	fmt.Println(err)
	data := []*design.Admin{}
	fmt.Println(res)
	for _, value := range *res {
		data = append(data, &design.Admin{
			Id:       int32(value.Id),
			UserName: value.UserName,
			PassWord: value.PassWord,
			Role: &design.Admin_Role{
				Name: value.Role.Name,
				Id:   int64(value.Role.Id),
			},
		})
	}
	return &design.AdminList{
		Code: 200,
		Msg:  "获取成功",
		Data: data,
		Page: nil,
	}, nil
}

func (self AdminService) DeleteAdmin(ctx context.Context, message *design.DeleteAdminMessage) (*design.BaseRespMessage, error) {
	id := message.Id

	o := orm.NewOrm()
	o.Delete(&database.User{
		Id: int(id),
	})
	return &design.BaseRespMessage{
		Code: 200,
		Msg:  "删除成功",
	}, nil

}

func (self AdminService) AddAdminService(ctx context.Context, message *design.AddAdminMessage) (*design.BaseRespMessage, error) {
	fmt.Println(message)

	user := database.User{
		UserName: message.UserName,
		PassWord: message.PassWord,
		Role: &database.Role{
			Id: int(message.RoleId),
		},
	}

	o := orm.NewOrm()

	row, e := o.Insert(&user)
	fmt.Println(row)
	fmt.Println(e)
	result := &design.BaseRespMessage{
		Code: 200,
		Msg:  "添加成功",
	}

	return result, nil
}

func (self *AdminService) UpdateAdminService(ctx context.Context, msg *design.UpdateAdminMessage) (*design.BaseRespMessage, error) {
	o := orm.NewOrm()
	fileter := o.QueryTable("user").Filter("Id", msg.Id)
	var e error = nil
	if len(msg.PassWord) == 0 {
		_, e = fileter.Update(orm.Params{
			"Role":int(msg.RoleId),
		})
	} else {
		_, e = fileter.Update(orm.Params{
			"pass_word": msg.PassWord,
			"role_id":int(msg.RoleId),
		})
	}

	if e != nil{
		return &design.BaseRespMessage{
			Code: 500,
			Msg: e.Error(),
		}, nil
	}

	return &design.BaseRespMessage{
		Code: 200,
		Msg:  "修改成功",
	}, nil
}
